/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.MarcasVehiculo;
import com.camachosanchez.bean.TiposEje;
import com.camachosanchez.bean.TiposVehiculo;
import com.camachosanchez.bean.Vehiculos;
import com.camachosanchez.controler.jdbc.TipoVehiculoJdbcControler;
import com.camachosanchez.controler.jpa.MarcasVehiculoJpaController;
import com.camachosanchez.gui.table.RenderizadorTabla;
import com.camachosanchez.gui.table.TableSorter;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.SQLUtil;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;
import net.coderazzi.filters.gui.TableFilterHeader;

/**
 *
 * @author ZULLY
 */
public class DialogoBusquedaUnidad extends javax.swing.JDialog {

    private DefaultTableModel dm;
    private RenderizadorTabla render;
    private RegistroEgresos buscador;

    /**
     * Creates new form DialogoBusquedaUnidad
     */
    public DialogoBusquedaUnidad(RegistroEgresos guiRegistro, java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.buscador = guiRegistro;
        llenarListasDesplegables();

        dm = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int col) {
                return false;
            }

            @Override
            public Class getColumnClass(int c) {
                return String.class;
            }
        };
        dm.setDataVector(new Object[][]{}, new Object[]{"", "ID", "PLACA", "CÓDIGO", "MARCA", "TIPO", "MODELO", "RAZÓN SOCIAL"});
        TableSorter tableSorter = new TableSorter(dm, tabla.getTableHeader());
        tabla.setModel(tableSorter);
        TableFilterHeader filterHeader = new TableFilterHeader();
        filterHeader.setTable(tabla);
        tabla.getTableHeader().setReorderingAllowed(false);
        ocultarColumnaCodigo();
        tabla.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    int fila = tabla.getSelectedRow();
                    if (fila >= 0) {
                        Vehiculos unidad = new Vehiculos();
                        unidad.setId(Integer.parseInt(dm.getValueAt(fila, 1).toString()));
                        unidad.setPlaca(dm.getValueAt(fila, 2).toString());
                        unidad.setCodBarras(dm.getValueAt(fila, 3).toString());
                        buscador.setUnidad(unidad);
                        cerrar();
                    }
                }
            }
        });
        render = new RenderizadorTabla();
        tabla.setDefaultRenderer(String.class, render);
        setSize(800, 400);
        this.setLocationRelativeTo(null);
    }

    private void cerrar() {
        this.dispose();
    }

    private void ocultarColumnaCodigo() {
        GUIUtil.SetAnchoColumnas(tabla);
        tabla.getColumnModel().getColumn(1).setMinWidth(0);
        tabla.getColumnModel().getColumn(1).setMaxWidth(0);
        tabla.getColumnModel().getColumn(1).setPreferredWidth(0);
    }

    private void llenarListasDesplegables() {
        TipoVehiculoJdbcControler tipos_vehiculo_dao = new TipoVehiculoJdbcControler();
        MarcasVehiculoJpaController marcas_vehiculo_dao = new MarcasVehiculoJpaController(null);
        List<TiposVehiculo> tipos_vehiculos = tipos_vehiculo_dao.findAll();
        tipos_vehiculos.add(0, null);
        List<MarcasVehiculo> marcas_vehiculos = marcas_vehiculo_dao.findMarcasVehiculoEntities();
        marcas_vehiculos.add(0, null);
        cmbTipo.setModel(new DefaultComboBoxModel(tipos_vehiculos.toArray()));
        cmbMarca.setModel(new DefaultComboBoxModel(marcas_vehiculos.toArray()));
        if (cmbTipo.getSelectedItem() != null) {
            TiposVehiculo tipoSeleccionado = (TiposVehiculo) cmbTipo.getSelectedItem();
            List<TiposEje> ejes = tipoSeleccionado.getTiposEjeList();
            List<TiposEje> ejesActivos = new ArrayList<TiposEje>();
            for (TiposEje item : ejes) {
                if (item.getActivo()) {
                    ejesActivos.add(item);
                }
            }
            ejesActivos.add(0, null);
            cmbModelo.setModel(new DefaultComboBoxModel(ejesActivos.toArray()));
        } else {
            cmbModelo.setModel(new DefaultComboBoxModel());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtPlaca = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        cmbMarca = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        cmbTipo = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        cmbModelo = new javax.swing.JComboBox();
        btnBuscar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Búsqueda de Unidad ::.");
        setResizable(false);
        getContentPane().setLayout(new java.awt.BorderLayout(5, 5));

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setText("Placa:");
        jPanel1.add(jLabel1);

        txtPlaca.setMinimumSize(new java.awt.Dimension(70, 20));
        txtPlaca.setPreferredSize(new java.awt.Dimension(80, 20));
        txtPlaca.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPlacaKeyReleased(evt);
            }
        });
        jPanel1.add(txtPlaca);

        jLabel2.setText("Código:");
        jPanel1.add(jLabel2);

        txtCodigo.setMinimumSize(new java.awt.Dimension(70, 20));
        txtCodigo.setPreferredSize(new java.awt.Dimension(80, 20));
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoKeyReleased(evt);
            }
        });
        jPanel1.add(txtCodigo);

        jLabel4.setText("Marca:");
        jPanel1.add(jLabel4);

        cmbMarca.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbMarca.setPreferredSize(new java.awt.Dimension(110, 20));
        cmbMarca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbMarcaActionPerformed(evt);
            }
        });
        cmbMarca.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cmbMarcaKeyPressed(evt);
            }
        });
        jPanel1.add(cmbMarca);

        jLabel3.setText("Tipo:");
        jPanel1.add(jLabel3);

        cmbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbTipo.setPreferredSize(new java.awt.Dimension(100, 20));
        cmbTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTipoActionPerformed(evt);
            }
        });
        cmbTipo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cmbTipoKeyPressed(evt);
            }
        });
        jPanel1.add(cmbTipo);

        jLabel5.setText("Modelo:");
        jPanel1.add(jLabel5);

        cmbModelo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbModelo.setPreferredSize(new java.awt.Dimension(130, 20));
        cmbModelo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbModeloActionPerformed(evt);
            }
        });
        jPanel1.add(cmbModelo);

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/buscar.png"))); // NOI18N
        btnBuscar.setToolTipText("Buscar");
        btnBuscar.setBorder(null);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        jPanel1.add(btnBuscar);

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 4, 4, 4));
        jPanel2.setLayout(new java.awt.BorderLayout(5, 5));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tabla.setRowHeight(22);
        tabla.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tabla);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
        buscar();
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void buscar() {
        Vehiculos unidad = new Vehiculos();
        unidad.setPlaca(txtPlaca.getText());
        unidad.setCodBarras(txtCodigo.getText());
        MarcasVehiculo marca = (MarcasVehiculo) cmbMarca.getSelectedItem();
        TiposVehiculo tipo = (TiposVehiculo) cmbTipo.getSelectedItem();
        TiposEje modelo = (TiposEje) cmbModelo.getSelectedItem();
        unidad.setIdMarca(marca);
        unidad.setIdTipo(tipo);
        unidad.setIdTipoEje(modelo);
        List<Vehiculos> unidades = SQLUtil.getListaUnidadesXCampo(unidad);
        llenarTabla(unidades);
    }

    private void cmbTipoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbTipoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            cmbModelo.requestFocusInWindow();
        }
    }//GEN-LAST:event_cmbTipoKeyPressed

    private void cmbTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTipoActionPerformed
        // TODO add your handling code here:
        if (cmbTipo.getSelectedItem() != null) {
            TiposVehiculo tipoSeleccionado = (TiposVehiculo) cmbTipo.getSelectedItem();
            List<TiposEje> ejes = tipoSeleccionado.getTiposEjeList();
            List<TiposEje> ejesActivos = new ArrayList<TiposEje>();
            for (TiposEje item : ejes) {
                if (item.getActivo()) {
                    ejesActivos.add(item);
                }
            }
            if (!ejes.isEmpty()) {
                ejesActivos.add(0, null);
                cmbModelo.setModel(new DefaultComboBoxModel(ejesActivos.toArray()));
            } else {
                cmbModelo.setModel(new DefaultComboBoxModel());
            }
        } else {
            cmbModelo.setModel(new DefaultComboBoxModel());
        }
        buscar();
    }//GEN-LAST:event_cmbTipoActionPerformed

    private void cmbMarcaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbMarcaKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            cmbTipo.requestFocusInWindow();
        }
    }//GEN-LAST:event_cmbMarcaKeyPressed

private void txtPlacaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPlacaKeyReleased
// TODO add your handling code here:
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        buscar();
    }
}//GEN-LAST:event_txtPlacaKeyReleased

private void txtCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyReleased
// TODO add your handling code here:
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        buscar();
    }
}//GEN-LAST:event_txtCodigoKeyReleased

private void cmbMarcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbMarcaActionPerformed
// TODO add your handling code here:
    buscar();
}//GEN-LAST:event_cmbMarcaActionPerformed

private void cmbModeloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbModeloActionPerformed
// TODO add your handling code here:
    buscar();
}//GEN-LAST:event_cmbModeloActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JComboBox cmbMarca;
    private javax.swing.JComboBox cmbModelo;
    private javax.swing.JComboBox cmbTipo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtPlaca;
    // End of variables declaration//GEN-END:variables

    private void llenarTabla(List<Vehiculos> lista) {
        Iterator results = lista.iterator();
        dm.setRowCount(0);
        while (results.hasNext()) {
            Vehiculos unidad = (Vehiculos) results.next();
            Object[] tupla = new Object[8];
            tupla[0] = "";
            tupla[1] = unidad.getId();
            tupla[2] = unidad.getPlaca();
            tupla[3] = unidad.getCodBarras();
            tupla[4] = unidad.getIdMarca().getNombre();
            tupla[5] = unidad.getIdTipo().getNombre();
            tupla[6] = unidad.getIdTipoEje().getNombre();
            tupla[7] = unidad.getIdFlotilla().getNombre();
            dm.addRow(tupla);
        }
        ocultarColumnaCodigo();
    }
}
